package com.uam.handler;

import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.uam.common.config.UAMConfig;
import com.uam.common.constant.Constants;
import com.uam.web.common.model.Result;
import com.uam.web.common.utils.AsyncFactory;
import com.uam.web.common.utils.AsyncManager;
import com.uam.web.common.utils.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证过程中失败，捕获到异常，封装成统一的响应体格式返回
 * @Author GoryLee
 * @Date 2022/12/7 20:44
 * @Version 1.0
 */
@Component
public class AuthenticationEntryPointHandler implements AuthenticationEntryPoint {

    @Autowired
    private UAMConfig uamConfig;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {
        if (uamConfig.getLoginURL().equalsIgnoreCase(request.getRequestURI())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(request.getParameter("loginName"), "", Constants.FAIL, Constants.LOGIN_TITLE, Constants.LOGIN_MSG_ERROR));
        }
        Result<Object> result = Result.createError(HttpStatus.HTTP_UNAUTHORIZED, "认证失败请重新登录");
        String jsonString = JSON.toJSONString(result);
        WebUtil.renderString(response,jsonString);
    }
}
